package com.example.gobang.service;

import com.example.gobang.constant.Constants;
import com.example.gobang.mapper.UserMapper;
import com.example.gobang.model.UserInfo;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public UserInfo selectByName(String userName) {
        return userMapper.selectByName(userName);
    }

    public UserInfo selectById(int userId) {
        return userMapper.selectById(userId);
    }

    public String isCorrectCaptcha(String captcha, HttpSession session) {
        // 获取存储的验证码和生成时间
        String code = (String) session.getAttribute(Constants.CAPTCHA_KEY);
        Date createTime = (Date) session.getAttribute(Constants.CAPTCHA_DATE);
        // 判断验证码是否正确（验证码一般忽略大小写）
        if(captcha.equalsIgnoreCase(code)) {
            // 判断验证码是否超时
            if(createTime == null || System.currentTimeMillis() - createTime.getTime() < Constants.EXPIRATION_TIME) {
                return null;
            }
            return "验证码已超时";
        }
        return "验证码错误";
    }

    public int insertUser(String userName, String password) {
        return userMapper.insertUser(userName, password);
    }
}
